import React, { createContext, useState, useEffect, useContext } from 'react';
import axios from 'axios';

// 创建管理员认证上下文
const AdminAuthContext = createContext();

// 管理员认证提供者组件
export const AdminAuthProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [loading, setLoading] = useState(true);

  // 初始化时检查本地存储的token
  useEffect(() => {
    const checkAuth = async () => {
      try {
        const token = localStorage.getItem('admin_token');
        if (token) {
          // 设置请求头中的Authorization
          axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
          // 验证token是否有效
          const response = await axios.get('/admin/auth/verify');
          setCurrentUser(response.data.user);
        }
      } catch (error) {
        // Token无效或过期，清除本地存储
        localStorage.removeItem('admin_token');
        delete axios.defaults.headers.common['Authorization'];
      } finally {
        setLoading(false);
      }
    };

    checkAuth();
  }, []);

  // 管理员登录方法
  const login = async (username, password) => {
    try {
      const response = await axios.post('/admin/auth/login', {
        username,
        password
      });

      // 保存token到本地存储
      const { token, refreshToken, user } = response.data;
      localStorage.setItem('admin_token', token);
      localStorage.setItem('admin_refresh_token', refreshToken);
      
      // 设置请求头
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      
      // 更新当前用户状态
      setCurrentUser(user);
      
      return user;
    } catch (error) {
      const errorMessage = error.response?.data?.message || '登录失败，请检查用户名和密码';
      throw new Error(errorMessage);
    }
  };

  // 管理员登出方法
  const logout = async () => {
    try {
      // 调用后端登出接口
      await axios.post('/admin/auth/logout');
    } catch (error) {
      console.error('登出请求失败:', error);
    } finally {
      // 清除本地存储和状态
      localStorage.removeItem('admin_token');
      localStorage.removeItem('admin_refresh_token');
      delete axios.defaults.headers.common['Authorization'];
      setCurrentUser(null);
    }
  };

  // 刷新token
  const refreshToken = async () => {
    try {
      const refreshToken = localStorage.getItem('admin_refresh_token');
      if (!refreshToken) {
        throw new Error('无刷新令牌');
      }

      const response = await axios.post('/admin/auth/refresh', {
        refreshToken
      });

      const { token: newToken, refreshToken: newRefreshToken } = response.data;
      localStorage.setItem('admin_token', newToken);
      localStorage.setItem('admin_refresh_token', newRefreshToken);
      axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`;
      
      return newToken;
    } catch (error) {
      // 刷新失败，清除认证状态
      logout();
      throw new Error('令牌刷新失败，请重新登录');
    }
  };

  // 提供的上下文值
  const value = {
    currentUser,
    loading,
    login,
    logout,
    refreshToken,
    isAuthenticated: !!currentUser
  };

  return (
    <AdminAuthContext.Provider value={value}>
      {children}
    </AdminAuthContext.Provider>
  );
};

// 自定义Hook，方便组件使用管理员认证上下文
export const useAdminAuth = () => {
  const context = useContext(AdminAuthContext);
  if (context === undefined) {
    throw new Error('useAdminAuth must be used within an AdminAuthProvider');
  }
  return context;
};